package com.example.sxproject.controller;

import com.example.sxproject.pojo.User;
import com.example.sxproject.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private UserService userService;

    // 上传目录路径
    //private static final String UPLOAD_DIR = "F:/SxProject/src/main/resources/static/img";
    private static final String UPLOAD_DIR = "src/main/resources/static/img";

    @PostMapping("/files")
    public String handleAvatarUpload(@RequestParam("avatar") MultipartFile avatar, HttpSession session) {

        User user = (User) session.getAttribute("user");

        // 处理文件上传逻辑
        if (!avatar.isEmpty()) {
            try {
                // 获取文件的原始名称
                String originalFileName = avatar.getOriginalFilename();

                user.setPhoto(originalFileName); // 设置用户头像名称
                // 更新到数据库
                userService.updateInformation(user);

                // 构建上传目标路径
                Path uploadPath = Paths.get(UPLOAD_DIR, originalFileName);

                // 将文件保存到指定路径
                Files.write(uploadPath, avatar.getBytes());

                // 返回成功上传的消息
                return "Avatar uploaded successfully: " + originalFileName;
            } catch (Exception e) {
                // 处理文件保存异常
                return "Failed to upload avatar: " + e.getMessage();
            }
        } else {
            // 如果文件为空，返回上传失败消息
            return "Avatar upload failed because the file was empty.";
        }
    }
}